package com.hansming.bss.modules.sfc.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.impl.util.json.JSONArray;
import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hansming.bss.common.config.Global;
import com.hansming.bss.common.utils.IdGen;
import com.hansming.bss.common.utils.StringUtils;
import com.hansming.bss.common.web.BaseController;
import com.hansming.bss.modules.sfc.entity.Bindpcinfo;
import com.hansming.bss.modules.sfc.entity.CarInfo;
import com.hansming.bss.modules.sfc.entity.Contacts;
import com.hansming.bss.modules.sfc.entity.Customer;
import com.hansming.bss.modules.sfc.entity.CustomerScoreLog;
import com.hansming.bss.modules.sfc.entity.Line;
import com.hansming.bss.modules.sfc.entity.Order;
import com.hansming.bss.modules.sfc.entity.OrderItem;
import com.hansming.bss.modules.sfc.entity.PcUser;
import com.hansming.bss.modules.sfc.entity.Traveller;
import com.hansming.bss.modules.sfc.entity.WxUser;
import com.hansming.bss.modules.sfc.service.CarInfoService;
import com.hansming.bss.modules.sfc.service.ContactsService;
import com.hansming.bss.modules.sfc.service.CustomerScoreLogService;
import com.hansming.bss.modules.sfc.service.CustomerService;
import com.hansming.bss.modules.sfc.service.LineService;
import com.hansming.bss.modules.sfc.service.OrderItemService;
import com.hansming.bss.modules.sfc.service.OrderService;
import com.hansming.bss.modules.sfc.service.PcUserService;
import com.hansming.bss.modules.sfc.service.SuggestService;
import com.hansming.bss.modules.sfc.service.TravellerService;
import com.hansming.bss.modules.sfc.service.WxUserService;
import com.hansming.bss.modules.sfc.util.AccountsCheckUtil;
import com.hansming.bss.modules.sfc.util.CarTimeHelp;
import com.hansming.bss.modules.sfc.util.CommUtil;
import com.hansming.bss.modules.sfc.util.DateHelper;
import com.hansming.bss.modules.sfc.util.PageBean;
import com.hansming.bss.modules.sfc.util.TimeUtil;



@Controller
@RequestMapping(value = "/my")
public class MineController extends BaseController{
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ContactsService contactsService;
	
	@Autowired
	private CarInfoService carinfoService;
	
	@Autowired
	private LineService	lineService;
	
	@Autowired
	private OrderItemService orderitemService;
	
	@Autowired
	private CustomerScoreLogService customerscorelogService;
	
	@Autowired
	private TravellerService travellerService;
	
	@Autowired
	private SuggestService suggestService;
	
	@Autowired
	private PcUserService pcuserService;

	@Autowired
	private CustomerScoreLogService scorelogService;
	
	@Autowired
	private WxUserService wxUserService;
	
	//我的首页的信息
	@RequestMapping(value="/info")
	public		void		getindexinfo(HttpServletRequest request, HttpServletResponse response) throws IOException{
			response.setCharacterEncoding("UTF-8");
		    response.setHeader("Cache-Control", "no-cache");
		    PrintWriter out = response.getWriter();
	        JSONObject jsonObject = new JSONObject();
	        JSONObject datas = new  JSONObject();
	        String code = "1";								//返回前台的消息状态
			String msg = "传递成功";								//返回前台的消息
		    HttpSession session = request.getSession();
		    String token = (String)session.getAttribute("token");
		    Customer user = customerService.selectbypcusertoken(token);
		    datas.put("score", user.getScore());
		    if(!user.getNick().equals("")){
		    	datas.put("nick", user.getNick());
		    }else{
		    	datas.put("nick", "");
		    }
		    if(!user.getShowurl().equals("")){
		    	datas.put("showurl", Global.getBasePath()+user.getShowurl());
		    }else{
		    	 datas.put("showurl", "");
		    }
		    if(!user.getPhone().equals("")){
		    	datas.put("phone",user.getPhone());
		    }else{
		    	datas.put("phone","未绑定手机");
		    }
		    if(!user.getEmail().equals("")){
		    	datas.put("email",user.getEmail());
		    }else{
		    	datas.put("email", "");
		    }
		    //得到四个联系人
		    JSONArray ja1 = new JSONArray();
		    List<Contacts> contacts = contactsService.getContactsByUserIdLimit4(user.getId());
		    for(Contacts c:contacts){
		    	JSONObject jo = new JSONObject();
		    	jo.put("name",c.getCname());
		    	jo.put("phone",c.getPhone());
		    	ja1.put(jo);
		    }
		    datas.put("contacts", contacts);
		    //得到四个游客的简要信息
		    JSONArray ja2= new JSONArray();
		    List<Traveller> travellers = travellerService.getTravellersByUseridlimit4(user.getId());
		    for(Traveller t:travellers){
		    	JSONObject jo = new JSONObject();
		    	jo.put("name",t.getName());
		    	jo.put("phone",t.getIdentnum());
		    	ja2.put(jo);
		    }
		    datas.put("travellers",ja2 );
			jsonObject.put("code", code);
			jsonObject.put("msg", msg);
			jsonObject.put("data", datas);
			out.print(jsonObject.toString());
			out.flush();
			out.close();
	}
	
	
	//当state为空字符是为查询所有订单。state为1时为待支付的订单，2，带出行，3，出行中的订单，4，已完成，5,
	@RequestMapping(value="/allorder")
	public void getOrderInfo(HttpServletRequest request, HttpServletResponse response,String state) throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        JSONArray datas = new  JSONArray();
        String code = "1";								//返回前台的消息状态
		String msg = "传递成功";								//返回前台的消息
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		Customer user = customerService.selectbypcusertoken(token); 
		List<Order> orders = orderService.selectOrderByShowState(user.getId(), state);
		for(int i=0;i<3;i++){
			if(orders.get(i).getType().equals("1")){
				JSONObject jo  = new JSONObject();
				CarInfo car = carinfoService.get(orders.get(i).getCarinfo().getId());
				 jo.put("id",orders.get(i).getId());
				 jo.put("type",orders.get(i).getType());
				 jo.put("num",orders.get(i).getNum());
				 jo.put("state",orders.get(i).getState() );
				 jo.put("price", orders.get(i).getPrice());
				 jo.put("productname", orders.get(i).getProductname());
				 jo.put("picture",Global.getBasePath()+car.getShowurl() );
				 jo.put("begindate",orders.get(i).getBeginDate());
				 jo.put("enddate", orders.get(i).getEndDate());
				 jo.put("begintime", CarTimeHelp.changetotime(orders.get(i).getBegintime()));
				 jo.put("endtime", CarTimeHelp.changetotime(orders.get(i).getEndtime()));
				 jo.put("city",car.getCity());		
				datas.put( jo);
			}
			if(orders.get(i).getType().equals("2")){
				JSONObject jo = new JSONObject();
				Line line = lineService.get(orders.get(i).getLine().getId());
				jo.put("id",orders.get(i).getId());
				jo.put("type", orders.get(i).getType());
				jo.put("num",orders.get(i).getNum());
				jo.put("state",orders.get(i).getState() );
				jo.put("price", orders.get(i).getPrice());
				jo.put("productname", line.getTitle());
				jo.put("picture",Global.getBasePath()+line.getShowurl());
				jo.put("begindate",orders.get(i).getBeginDate());
				jo.put("enddate", orders.get(i).getEndDate());	
				datas.put( jo);
			}
		}	
		jsonObject.put("code", code);
		jsonObject.put("msg", msg);
		jsonObject.put("data", datas);
		out.print(jsonObject.toString());
		out.flush();
		out.close();
	}
	
	
	//得到更多
	
	
	@RequestMapping(value="/getorderbytype")
	public void getorderbytype(HttpServletRequest request,HttpServletResponse response,String type,String state)throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        JSONArray datas = new  JSONArray();
        String code = "1";								//返回前台的消息状态
		String msg = "传递成功";								//返回前台的消息
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		Customer user = customerService.selectbypcusertoken(token);
		List<Order> orderlist = orderService.findOrderBytypeandstate(user.getId(),state,type);
		for(Order o:orderlist){
			if(o.getType().equals("1")){
				JSONObject jo  = new JSONObject();
				CarInfo car = carinfoService.get(o.getCarinfo().getId());
				 jo.put("id",o.getId());
				 jo.put("type",o.getType());
				 jo.put("num",o.getNum());
				 jo.put("state",o.getState() );
				 jo.put("price", o.getPrice());
				 jo.put("productname", o.getProductname());
				 jo.put("picture",Global.getBasePath()+car.getShowurl() );
				 jo.put("begindate",o.getBeginDate());
				 jo.put("enddate",o.getEndDate());
				 jo.put("begintime", CarTimeHelp.changetotime(o.getBegintime()));
				 jo.put("endtime", CarTimeHelp.changetotime(o.getEndtime()));
				 jo.put("city",car.getCity());		
				datas.put(jo);
			}
			if(o.getType().equals("2")){
				JSONObject jo = new JSONObject();
				Line line = lineService.get(o.getLine().getId());
				jo.put("id",o.getId());
				jo.put("type", o.getType());
				jo.put("num",o.getNum());
				jo.put("state",o.getState() );
				jo.put("price", o.getPrice());
				jo.put("productname", line.getTitle());
				jo.put("picture",Global.getBasePath()+line.getShowurl());
				jo.put("begindate",o.getBeginDate());
				jo.put("enddate", o.getEndDate());	
				datas.put( jo);
			}
		}
		
		
		
		jsonObject.put("code", code);
		jsonObject.put("msg", msg);
		jsonObject.put("data", datas);
		out.print(jsonObject.toString());
		out.flush();
		out.close();
	}
	
	
	
	
	
	
	
					
	
	@RequestMapping(value="/scorelog")
	public void getscoreinclude(HttpServletRequest request, HttpServletResponse response) throws IOException{	
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        JSONObject datas = new  JSONObject();
        String code = "1";								//返回前台的消息状态
		String msg = "传递成功";								//返回前台的消息
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		Customer user = customerService.selectbypcusertoken(token); 
		List<CustomerScoreLog> scores = scorelogService.getCustomerScoreLogsByCusid(user.getId());
		
		
		
		
		
		
		
		
		jsonObject.put("code", code);
		jsonObject.put("msg", msg);
		jsonObject.put("data", datas);
		out.print(jsonObject.toString());
		out.flush();
		out.close();
	}
	
	
	
	//阿里支付异步跳转的页面
	@RequestMapping(value="/returnUrl")
	public String turnToalipayUrl(HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes,Model model){
		HttpSession session = request.getSession();
		String orderid = (String)session.getAttribute("orderid");
		Order order = orderService.get(orderid);
		if(order != null){
			String type = order.getType();
			if(type.equals("1")){
				//正常跳转租车
				CarInfo car = carinfoService.get(order.getCarinfo());
				order.setCarinfo(car);
				model.addAttribute("order",order);
				
				String starttime = "00:00";
				String endtime   = "00:00";
				try {
					starttime = CarTimeHelp.changetotime(order.getBegintime())+"   "+TimeUtil.getweekday(order.getBeginDate());
					endtime = CarTimeHelp.changetotime(order.getEndtime())+"   "+TimeUtil.getweekday(order.getEndDate());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				model.addAttribute("starttime",starttime);
				model.addAttribute("endtime",endtime);
				List<OrderItem> lo = orderitemService.getOrderItemsByOrderId(order.getId());
				model.addAttribute("orderitem", lo);
			
				return "modules/sfc/pcsofangche/rent/rentrepay/rentorderinfo";
			}else if(type.equals("2")){
				//正常跳转线路
				Line line = lineService.get(order.getLine());
				order.setLine(line);
				model.addAttribute("order",order);
				String starttime = "00:00";
				String endtime   = "00:00";
				try {
					starttime = TimeUtil.getweekday(order.getBeginDate());
					endtime = TimeUtil.getweekday(order.getEndDate());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				model.addAttribute("starttime",starttime);
				model.addAttribute("endtime",endtime);
				List<OrderItem> lo = orderitemService.getOrderItemsByOrderId(order.getId());
				model.addAttribute("orderitem",lo );
				List<Traveller> list = travellerService.findTravellersByOrderId(order.getId());
				model.addAttribute("traveller",list);
				
				return "modules/sfc/pcsofangche/line/linerepay/lineorderinfo";
			}else{
				//当出异常时候的跳转
								
				return "redirect:/";
			}	
		}else{
			
			
			return "redirect:/";
		}
	}
	
	//测试支付后订单信息展示页面
	@RequestMapping(value="/testorderinfo")
	public String getorderinfo(HttpServletRequest request,RedirectAttributes redirectAttributes,Model model){
//		Order order = orderService.get("8d2e436a35314a7fae5ff2936eb08ae3");//租车订单
		Order order =orderService.get("9ebe8e7a0fe341b784050a46a2b090d9");
		if(order != null){
			String type = order.getType();
			if(type.equals("1")){
				//正常跳转租车
				CarInfo car = carinfoService.get(order.getCarinfo());
				order.setCarinfo(car);
				model.addAttribute("order",order);
				
				String starttime = "00:00";
				String endtime   = "00:00";
				try {
					starttime = CarTimeHelp.changetotime(order.getBegintime())+"   "+TimeUtil.getweekday(order.getBeginDate());
					endtime = CarTimeHelp.changetotime(order.getEndtime())+"   "+TimeUtil.getweekday(order.getEndDate());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				model.addAttribute("starttime",starttime);
				model.addAttribute("endtime",endtime);
				List<OrderItem> lo = orderitemService.getOrderItemsByOrderId(order.getId());
				model.addAttribute("orderitem", lo);
			
				return "modules/sfc/pcsofangche/rent/rentrepay/rentorderinfo";
			}else if(type.equals("2")){
				//正常跳转线路
				Line line = lineService.get(order.getLine());
				order.setLine(line);
				model.addAttribute("order",order);
				String starttime = "00:00";
				String endtime   = "00:00";
				try {
					starttime = TimeUtil.getweekday(order.getBeginDate());
					endtime = TimeUtil.getweekday(order.getEndDate());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				model.addAttribute("starttime",starttime);
				model.addAttribute("endtime",endtime);
				List<OrderItem> lo = orderitemService.getOrderItemsByOrderId(order.getId());
				model.addAttribute("orderitem",lo );
				List<Traveller> list = travellerService.findTravellersByOrderId(order.getId());
				model.addAttribute("traveller",list);
				
				return "modules/sfc/pcsofangche/line/linerepay/lineorderinfo";
			}else{
				//当出异常时候的跳转
								
				return "redirect:/";
			}	
		}else{
			
			
			return "redirect:/";
		}
	}

	/*
	 * PC个人中心临时接口
	 * 
	 */
	@RequestMapping(value="/sliorder")
	public void getSmOrderBySt(HttpServletRequest request,HttpServletResponse response,String ordernum,String type,Integer page) throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        JSONArray datas = new  JSONArray();		//返回到前台的具体的价格日期信息json
		String code = "1";										//返回前台的消息状态
		String msg = "访问成功";								//返回前台的消息
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 if(ordernum == null && "".equals(ordernum)){
			 code = "2";
			 msg = "参数缺失";
		 }
		 if(type == null && "".equals(type)){
			 code = "2";
			 msg = "参数缺失";
		 }
		 if(page == null && page == 0){
			 code = "2";
			 msg = "参数缺失";
		 }
			if(token != null && !token.equals("")){
				 Customer user = customerService.selectbypcusertoken(token); 
				 
				 if(user!=null){
				     PageBean pagebean = new PageBean();
					 pagebean.setPageSize(4);
					 pagebean.setPage(page);
					 int result = 0;
					 pagebean.setTotalCount(result);
					 Bindpcinfo bindpcinfo = customerService.selectBindinfoByPcUserId(user.getPcuserid());
					 List<Order> list =null;
					 if(bindpcinfo != null){
						 WxUser miniUser=wxUserService.get(bindpcinfo.getMiniappuserid());
						 String[] ids= new String[2];
						 ids[0]=miniUser.getUser().getId();
						 ids[1]=user.getId();
						 result = orderService.getsmOrdernumBysmt2(ordernum, type,ids);
						 pagebean.setTotalCount(result);
						 list=orderService.getsmOrderBysmt2(ordernum, type, pagebean,ids);
					 }else {
						 result = orderService.getsmOrdernumBysmt(ordernum, type,user.getId());
						 pagebean.setTotalCount(result);
						 list= orderService.getsmOrderBysmt(ordernum, type, pagebean,user.getId());
					 }
					 for(int i=0;i<list.size();i++){
						 JSONObject jo = new JSONObject();
						 if(list.get(i).getType().equals("1")){
							 CarInfo car = carinfoService.get(list.get(i).getCarinfo());
							 jo.put("id",list.get(i).getId());
							 jo.put("type",list.get(i).getType());
							 jo.put("num",list.get(i).getNum());
							 jo.put("state",list.get(i).getState());
							 jo.put("price", list.get(i).getPrice());
							 jo.put("productname", list.get(i).getProductname());					
							 jo.put("picture",Global.getBasePath()+car.getShowurl());
							 jo.put("begindate",list.get(i).getBeginDate());
							 jo.put("enddate",list.get(i).getEndDate());
							 jo.put("begintime", CarTimeHelp.changetotime(list.get(i).getBegintime()));
							 jo.put("endtime", CarTimeHelp.changetotime(list.get(i).getEndtime()));
							 jo.put("city",car.getCity());	
							 jo.put("createtime", dft.format(list.get(i).getCreateDate()));
						 } else if(list.get(i).getType().equals("2")){
							 Line line = lineService.get(list.get(i).getLine());
							 jo.put("id",list.get(i).getId());
							 jo.put("type", list.get(i).getType());
							 jo.put("num",list.get(i).getNum());
							 jo.put("state",list.get(i).getState() );
							 jo.put("price", list.get(i).getPrice());
							 jo.put("productname",line.getTitle());
							 jo.put("picture",Global.getBasePath()+line.getShowurl());
							 jo.put("city",line.getCity());
							 jo.put("begindate",list.get(i).getBeginDate());
							 jo.put("enddate", list.get(i).getEndDate());
							 jo.put("createtime",dft.format( list.get(i).getCreateDate()));
						 }
						 datas.put(jo);
					 }
					 jsonObject.put("pagesize", pagebean.getTotalPage()); 
				  }
			 }else{
				code = "2";
				msg = "用户未登录";
			 }
		
		jsonObject.put("code",code);
		jsonObject.put("msg", msg);
		jsonObject.put("data",datas);
		out.print(jsonObject.toString());
		out.flush();
		out.close();
	}
	
	
	
	
	/**
	 * XGP  个人中心-我的信息首页
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/detail")
	public		void		getMyinfoIndex(HttpServletRequest request, HttpServletResponse response) throws IOException{	
			response.setCharacterEncoding("UTF-8");
	        response.setHeader("Cache-Control", "no-cache");
	        PrintWriter out = response.getWriter();
	        JSONObject jsonObject = new JSONObject();
	        JSONObject datas = new  JSONObject();
	        String code = "1";								//返回前台的消息状态
			String msg = "传递成功";								//返回前台的消息
			HttpSession session = request.getSession();
			String token = (String)session.getAttribute("token");
			Customer user = customerService.selectbypcusertoken(token); 
			//Customer user = customerService.get("a4d6541d98ec4972900db1a80fde22ee");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(user!=null){
				if(user.getNick() != null) {
					datas.put("nick", user.getNick());
				}else{
					datas.put("nick"," ");
				}
				
				if(user.getPcHeadImg() != null) {
					datas.put("pcHeadImg", user.getPcHeadImg());
				}else{
					datas.put("pcHeadImg"," ");
				}
				
				
				if(user.getRealname()!=null){	
					datas.put("realName", user.getRealname());
				}else{
					datas.put("realName"," ");
				}
				
				if( user.getGender() != 0){
					datas.put("gender",""+ user.getGender());
				}else{
					datas.put("gender"," ");
				}
				if(user.getBirthdate() != null){
					datas.put("birthdate", sdf.format(user.getBirthdate()));
				}else{
					datas.put("birthdate"," ");
				}
				if(user.getPhone() != null){
					datas.put("phone", user.getPhone());
				}else{
					datas.put("phone"," ");
				}
				if(user.getEmail() != null){
					datas.put("email", user.getEmail());
				}else{
					datas.put("email"," ");
				}
			}else{
				datas.put("name", "  ");
				datas.put("sex","  ");
				datas.put("birthdate", "  ");
				datas.put("phone", "  ");
				datas.put("email", " ");
				datas.put("nick", " ");
				datas.put("pcHeadImg", " ");
			}
			jsonObject.put("respCode", code);
			jsonObject.put("msg", msg);
			jsonObject.put("data", datas);
			
			response.setContentType("text/plain");
			response.setHeader("Cache-Control", "no-cache");
			response.setCharacterEncoding("UTF-8");
			PrintWriter writer = response.getWriter();
			writer.print(jsonObject);
	}
	
	
	/**
	 *  @author 24424
	 *   XGP-异步提交图片并返回路径
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping({"/uploadMineImg"})
	public void uploadMineImg(HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setHeader("Access-Control-Allow-Credentials", "false");
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "*");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
		
		JSONObject jsonObj = new JSONObject();
		String saveFilePathName=request.getSession().getServletContext().getRealPath("/") +
		"static"+File.separator+"pcsofangche"+File.separator+"my"+ File.separator + "img";
		
		Map mapDate=new HashMap<Object, Object>();
		
		try {
		
			CommUtil.createFolder(saveFilePathName);
			System.out.println(saveFilePathName);
			Map map=CommUtil.saveFileToServer(request, "mineImg", saveFilePathName, null, null);
			String contextPath = request.getContextPath().equals("/") ? "" : request.getContextPath();
	
	        String url = "http://" + request.getServerName();
	        if (CommUtil.null2Int(Integer.valueOf(request.getServerPort())) != 80)
	            url = url + ":" +CommUtil.null2Int(Integer.valueOf(request.getServerPort())) + contextPath;
	        else{
	            url = url + contextPath;
	        }
	        if (map.get("fileName") != ""){
	        	String imgPath=(String) map.get("fileName");
	        	mapDate.put("ImgPath", url+"/static/pcsofangche/my/img/"+imgPath);
			}
	        jsonObj.put("data", mapDate);	
			jsonObj.put("respCode", "1");
			jsonObj.put("msg", "提交成功!");
		}catch (Exception e) {
			e.printStackTrace();
			jsonObj.put("respCode", "0");
			jsonObj.put("msg", "出现错误，请求失败！");
		}
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObj);
	}
	
	/**
	 *  @author 24424
	 *   XGP-编辑用户信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping({"/updateUser"})
	public void updateUser(HttpServletRequest request,HttpServletResponse response,@RequestBody Customer user) throws IOException {
		JSONObject jsonObject = new JSONObject();
		JSONArray datas = new  JSONArray();		//返回到前台的具体的价格日期信息json
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		if(token != null && !token.equals("")){
			Customer customer = customerService.selectbypcusertoken(token);
			//Customer customer = customerService.get("a4d6541d98ec4972900db1a80fde22ee");
			if(user.getNick() != null && !user.getNick().equals("")) {
				customer.setNick(user.getNick());
			}
				 
			if(user.getPcHeadImg() != null) {
				customer.setPcHeadImg(user.getPcHeadImg());
			}
				
			if(user.getRealname()!=null){	
				customer.setRealname(user.getRealname());
			}
				
			if( user.getGender() != 0){
				customer.setGender(user.getGender());
			}
			if(user.getBirthdate() != null){
				customer.setBirthdate(user.getBirthdate());
			}
			if(user.getPhone() != null){
				customer.setPhone(user.getPhone());
			}
			if(user.getEmail() != null){
				customer.setEmail(user.getEmail());
			}
			customerService.update(customer);
			jsonObject.put("code","1");
			jsonObject.put("msg", "编辑成功");
		}else{
			jsonObject.put("code","2");
			jsonObject.put("msg", "用户未登录");
		}
		
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	
	/**
	 * XGP-联系人列表
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/contactList")
	public  void  getcontactslist(HttpServletRequest request, HttpServletResponse response)throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        JSONObject jsonObject = new JSONObject();
        JSONArray datas = new  JSONArray();
        String code = "1";								//返回前台的消息状态
		String msg = "传递成功";								//返回前台的消息
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		Customer user = customerService.selectbypcusertoken(token); 
		//Customer user = customerService.get("a4d6541d98ec4972900db1a80fde22ee");
		List<Contacts> contacts = contactsService.getContactsByuserId(user.getId());
		for(Contacts c:contacts){
			JSONObject jo = new JSONObject();
			jo.put("id",c.getId());
			jo.put("name",c.getCname());
			jo.put("type",c.getIdenttype());
			jo.put("num",c.getIdentnum());
			jo.put("phone", c.getPhone());
			jo.put("email", c.getEmail());
			if(c.getSex() != null) {
				jo.put("sex", c.getSex());
			}else {
				jo.put("sex", "");
			}
			datas.put(jo);
		}
		jsonObject.put("respCode", code);
		jsonObject.put("msg", msg);
		jsonObject.put("data", datas);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	
	/**
	 * XGP-联系人详情
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/contactDetail")
	public  void  contactDetail(HttpServletRequest request, HttpServletResponse response,@RequestBody Contacts con)throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        JSONObject jsonObject = new JSONObject();
        JSONArray datas = new  JSONArray();
        String code = "1";								//返回前台的消息状态
		String msg = "传递成功";								//返回前台的消息
		HttpSession session = request.getSession();
		con=contactsService.get(con.getId());
		
		JSONObject jo = new JSONObject();
		jo.put("id",con.getId());
		jo.put("name",con.getCname());
		jo.put("type",con.getIdenttype());
		jo.put("num",con.getIdentnum());
		jo.put("phone", con.getPhone());
		jo.put("email", con.getEmail());
		if(con.getSex() != null) {
			jo.put("sex", con.getSex());
		}else {
			jo.put("sex", "");
		}
		if(con.getBirthdate() != null) {
			jo.put("birthdate", DateHelper.convert2String(con.getBirthdate(), DateHelper.DATE_FORMATE));
		}else {
			jo.put("birthdate", "");
		}
		datas.put(jo);
		jsonObject.put("respCode", code);
		jsonObject.put("msg", msg);
		jsonObject.put("data", datas);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	
	/**
	 * XGP-新增或编辑联系人
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/contactAdd")
	public  void  contactAdd(HttpServletRequest request, HttpServletResponse response,@RequestBody Contacts contacts)throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
        Customer customer = customerService.selectbypcusertoken(token);
        //Customer customer = customerService.get("a4d6541d98ec4972900db1a80fde22ee");
        System.out.println("id------------------"+customer.getId());
        JSONObject jsonObject = new JSONObject();
		Contacts con=null;
		String code = "1";								//返回前台的消息状态
		String msg = "传递成功";		
		if(contacts.getId() != null && !contacts.getId().equals("")) {
			con=contactsService.get(contacts.getId());
		}else {
			con=new Contacts();
		}
		
		con.setCname(contacts.getCname());
		con.setSex(contacts.getSex());
		con.setBirthdate(contacts.getBirthdate());
		con.setIdenttype(contacts.getIdenttype());
		con.setIdentnum(contacts.getIdentnum());
		con.setPhone(contacts.getPhone());
		con.setEmail(contacts.getEmail());
		con.setCustomer(customer);
		con.setUser_id(customer.getId());
		
		contactsService.save(con);
		
		
		jsonObject.put("respCode", code);
		jsonObject.put("msg", msg);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	
	/**
	 * XGP-删除联系人
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/contactDel")
	public  void  contactDel(HttpServletRequest request, HttpServletResponse response,@RequestBody Contacts contacts)throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        JSONObject jsonObject = new JSONObject();
		Contacts con=null;
		String code = "1";								//返回前台的消息状态
		String msg = "删除成功!";		
		
		contactsService.delete(contacts);
		
		jsonObject.put("respCode", code);
		jsonObject.put("msg", msg);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	
	
	/**
	 * XGP-常用旅客列表
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/travellerList")
	public  void  travellerList(HttpServletRequest request, HttpServletResponse response)throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        JSONObject jsonObject = new JSONObject();
        JSONArray datas = new  JSONArray();
        String code = "1";								//返回前台的消息状态
		String msg = "传递成功";								//返回前台的消息
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		Customer user = customerService.selectbypcusertoken(token); 
		List<Traveller> travellers = travellerService.getTravelelrsByCustomerid(user.getId());
		for(Traveller t:travellers){
			JSONObject jo = new JSONObject();
			jo.put("id",t.getId());
			jo.put("name",t.getName());
			jo.put("type",t.getIdenttype());
			jo.put("num",t.getIdentnum());
			jo.put("phone", t.getPhone());
			jo.put("email", t.getEname());
			if(t.getGender() != null) {
				jo.put("sex", t.getGender());
			}else {
				jo.put("sex", "");
			}
			datas.put(jo);
		}
		jsonObject.put("respCode", code);
		jsonObject.put("msg", msg);
		jsonObject.put("data", datas);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	
	/**
	 * XGP-常用旅客详情
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/travellerDetail")
	public  void  travellerDetail(HttpServletRequest request, HttpServletResponse response,@RequestBody Traveller tra)throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        JSONObject jsonObject = new JSONObject();
        JSONArray datas = new  JSONArray();
        String code = "1";								//返回前台的消息状态
		String msg = "传递成功";								//返回前台的消息
		HttpSession session = request.getSession();
		tra=travellerService.get(tra.getId());
		
		JSONObject jo = new JSONObject();
		jo.put("id",tra.getId());
		jo.put("name",tra.getName());
		jo.put("type",tra.getIdenttype());
		jo.put("num",tra.getIdentnum());
		if(tra.getPhone() != null) {
			jo.put("phone", tra.getPhone());
		}else {
			jo.put("phone", "");
		}
		if(tra.getEname() != null) {
			jo.put("email", tra.getEname());
		}else {
			jo.put("email", "");
		}
		if(tra.getGender() != null) {
			jo.put("sex", tra.getGender());
		}else {
			jo.put("sex", "");
		}
		if(tra.getBirthday() != null) {
			jo.put("birthdate", tra.getBirthday());
		}else {
			jo.put("birthdate", "");
		}
		datas.put(jo);
		jsonObject.put("respCode", code);
		jsonObject.put("msg", msg);
		jsonObject.put("data", datas);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	/**
	 * XGP-新增或编辑常用旅客
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/travellerAdd")
	public  void  travellerAdd(HttpServletRequest request, HttpServletResponse response,@RequestBody Traveller traveller)throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        JSONObject jsonObject = new JSONObject();
        Traveller tra=null;
		String code = "1";								//返回前台的消息状态
		String msg = "传递成功";		
		
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
        Customer customer = customerService.selectbypcusertoken(token);
		
		if(traveller.getId() != null && !traveller.getId().equals("")) {
			tra=travellerService.get(traveller.getId());
		}else {
			tra=new Traveller();
		}
		
		tra.setName(traveller.getName());
		tra.setGender(traveller.getGender());
		tra.setBirthday(traveller.getBirthday());
		tra.setIdenttype(traveller.getIdenttype());
		tra.setIdentnum(traveller.getIdentnum());
		tra.setPhone(traveller.getPhone());
		tra.setEname(traveller.getEname());
		tra.setCustomer(customer);
		travellerService.save(tra);
		
		jsonObject.put("respCode", code);
		jsonObject.put("msg", msg);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	
	/**
	 * XGP-删除常用旅客
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/travellerDel")
	public  void  travellerDel(HttpServletRequest request, HttpServletResponse response,@RequestBody Traveller traveller)throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        JSONObject jsonObject = new JSONObject();
		Contacts con=null;
		String code = "1";								//返回前台的消息状态
		String msg = "传递成功";		
		
		travellerService.delete(traveller);
		
		jsonObject.put("respCode", code);
		jsonObject.put("msg", msg);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	/**
	 * @author 24424
	 * XGP-修改密码-手机
	 * @param request
	 * @param response
	 * @param map
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value="/updatePwd")
	public  void  updatePwd(HttpServletRequest request, HttpServletResponse response,@RequestBody Map<String,Object> map)throws IOException, ParseException{
		JSONObject jsonObject = new JSONObject();
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		Customer user = customerService.selectbypcusertoken(token); 
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date now = new Date();
		
		String code=(String) map.get("code");
		String phone=(String) map.get("phone");
		String newPwd=(String)map.get("newPwd");
		String confirmPwd=(String)map.get("confirmPwd");
		String respCode="1";
		String msg="";
		if(!newPwd.equals(confirmPwd)) {
			respCode="0";
			msg="密码输入不一致";
		}else {
			if(!"".equals(code) && code != null){
				String time = pcuserService.selectPcUserByPhone(phone, code);
				PcUser pcuser = pcuserService.selectPcUserByPhoneAndCode(phone, code);
				if(time != null && !"".equals(time) && pcuser != null){					
					long datetimenum = sdf.parse(sdf.format(sdf.parse(time))).getTime();
					long nowtimenum = sdf.parse(sdf.format(now)).getTime();
					long minutes = (nowtimenum-datetimenum)/1000;
					if(minutes < 300){//此处原判定条件为minutes > 300
						newPwd=AccountsCheckUtil.encodeByMD5(newPwd);
						pcuserService.updatepassworedbyphone(phone, newPwd);
						msg="修改成功!";
					}else {
						respCode="0";
						msg="验证码超时";
					}
				}else {
					respCode="0";
					msg="未知错误!!";
				}
			}else {
				respCode="0";
				msg="验证码不能为空!!";
			}
		}
		
		jsonObject.put("respCode", respCode);
		jsonObject.put("msg", msg);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
		
	}
	
	
	/**
	 * @author 24424
	 * XGP-获取用户手机号码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/getUserPhone")
	public  void  getUserPhone(HttpServletRequest request, HttpServletResponse response)throws IOException{
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        JSONObject jsonObject = new JSONObject();
        JSONArray datas = new  JSONArray();
        
        String code = "1";								//返回前台的消息状态
		String msg = "传递成功";								//返回前台的消息
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		Customer user = customerService.selectbypcusertoken(token); 
		PcUser pcUser=pcuserService.get(user.getPcuserid());
		JSONObject jo = new JSONObject();
		jo.put("phone",pcUser.getPhone());
		datas.put(jo);
		
		jsonObject.put("respCode", code);
		jsonObject.put("msg", msg);
		jsonObject.put("data", datas);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	
	
	/**
	 * @author 24424
	 * XGP-修改密码-原密码
	 * @param request
	 * @param response
	 * @param map
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value="/updatePwdByOld")
	public  void  updatePwdByOld(HttpServletRequest request, HttpServletResponse response,@RequestBody Map<String,Object> map)throws IOException, ParseException{
		JSONObject jsonObject = new JSONObject();
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		Customer user = customerService.selectbypcusertoken(token); 
		//Customer user = customerService.get("a4d6541d98ec4972900db1a80fde22ee");
		PcUser pcUser=pcuserService.get(user.getPcuserid());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date now = new Date();
		
		String pwd=(String) map.get("pwd");
		String newPwd=(String)map.get("newPwd");
		String confirmPwd=(String)map.get("confirmPwd");
		String respCode="1";
		String msg="";
		if(!newPwd.equals(confirmPwd)) {
			respCode="0";
			msg="密码输入不一致";
		}else {
			if(!"".equals(pwd) && pwd != null){
				String pwd2=AccountsCheckUtil.encodeByMD5(pwd);
				if(pwd2.equalsIgnoreCase(pcUser.getPassword())) {
					newPwd=AccountsCheckUtil.encodeByMD5(newPwd);
					String phone=pcUser.getPhone();
					pcuserService.updatepassworedbyphone(phone, newPwd);
					msg="修改成功!";
				}else {
					respCode="0";
					msg="原密码错误!!";
				}
			}else {
				respCode="0";
				msg="原密码不能为空!!";
			}
		}
		
		jsonObject.put("respCode", respCode);
		jsonObject.put("msg", msg);
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
		
	}
	
	
	
	/**
	 * 验证手机号码并修改
	 * @param request
	 * @param response
	 * @param map
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value="/codeVer")
	public  void  codeVer(HttpServletRequest request, HttpServletResponse response,@RequestBody Map<String,Object> map)throws IOException, ParseException{
		JSONObject jsonObject = new JSONObject();
		String code = (String) map.get("code");
		String phone=(String) map.get("phone");
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		Customer user = customerService.selectbypcusertoken(token); 
		//Customer user = customerService.get("a4d6541d98ec4972900db1a80fde22ee");
		PcUser pcUser=pcuserService.get(user.getPcuserid());
		int phoneCount=pcuserService.checkphone(phone);
		String respCode="1";
		String msg="";
		if(phoneCount > 0) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date now = new Date();
			if(!"".equals(code) && code != null){
				String time = pcuserService.selectPcUserByPhone(phone, code);
				if(time != null && !"".equals(time) && pcUser != null){				
					long datetimenum = sdf.parse(sdf.format(sdf.parse(time))).getTime();
					long nowtimenum = sdf.parse(sdf.format(now)).getTime();
					long minutes = (nowtimenum-datetimenum)/1000;
					if(minutes < 300){//此处原判定条件为minutes > 300
						user.setPhone(phone);
						pcUser.setPhone(phone);
						
						customerService.update(user);
						pcuserService.update(pcUser);
						msg="修改成功!";
					}else {
						respCode="0";
						msg="验证码超时";
					}
				}else {
					respCode="0";
					msg="未知错误!!";
				}
			}else {
				respCode="0";
				msg="验证码不能为空!!";
			}
			jsonObject.put("respCode", respCode);
			jsonObject.put("msg", msg);
		}else {
			jsonObject.put("respCode", 0);
			jsonObject.put("msg", "已有该手机用户！");
		}
		
		
		
		
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
		
	}
	

	@RequestMapping(value="/checkBindStatus")
	public  void  checkBindStatus(HttpServletRequest request, HttpServletResponse response)throws IOException, ParseException{
		JSONObject jsonObject = new JSONObject();
		HttpSession session = request.getSession();
		String token = (String)session.getAttribute("token");
		Customer user = customerService.selectbypcusertoken(token); 
		if(user!=null){
			Bindpcinfo bindpcinfo = customerService.selectBindinfoByPcUserId(user.getPcuserid());
			if(bindpcinfo != null){
				jsonObject.put("respCode", 1);
				jsonObject.put("msg", "绑定成功！");
			}else {
				jsonObject.put("respCode", 0);
				jsonObject.put("msg", "暂未绑定！");
			}
		}
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.print(jsonObject);
	}
	
	
	
	
	
	
	
	
	
}
